<script setup lang="ts">
import { http } from '@/apis'
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { ref } from 'vue'
import base64ToBlob from 'b64-to-blob'

//1. 头像弹层的显示和隐藏
const showAvatarSheet = ref(false)
const selectAvatarSheet = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    const data = await mk.pickerPhoto()
    onUpdateAvatar(data)
  } else if (index === 1) {
    const data = await mk.pickerCamera()
    onUpdateAvatar(data)
  }
}

//1.1 上传头像
const onUpdateAvatar = async (data: string) => {
  if (!data) return showToast('请选择图片')
  try {
    //1.1.1把base64编码转成图片文件
    const image = base64ToBlob(data, 'image/jpeg')
    // console.log(image)
    //1.1.2 把文件放入formData对象
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')

    //1.1.3 调用接口
    showLoadingToast({ message: '正在上传中...', duration: 0, forbidClick: true })
    const res = await http.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd)
    profile.value.avatar = res.data.result.avatar

    //1.1.4 修改原生侧头像
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast('头像上传成功')
  } catch (e) {
    showToast('头像上传失败')
  } finally {
    closeToast()
  }
}

// 2. 选择生日日期
const showBirthdayPopup = ref(false)
const onChangeBirthday = () => {
  // 2.1 隐藏弹层
  showBirthdayPopup.value = false
  profile.value.birthday = birthday.value.join('-')
}
//2.2 定义一个属性去和datePicker双向绑定
const now = new Date()
const birthday = ref([
  now.getFullYear().toString(),
  (now.getMonth() + 1).toString,
  now.getDate().toString()
])

// 3. 获取所在地
const areaColumns = ref<AreaColumns>()
const showLocationPopup = ref(false)
const getAreaColumns = async () => {
  const res = await mk.getAreaColumns()
  areaColumns.value = res
  // console.log(areaColumns.value)
}
getAreaColumns()
const onSelectedLocation = (data: { selectedValues: number[] }) => {
  // 3.1 隐藏弹层
  showLocationPopup.value = false
  //3.2 根据省市区的编码获取省市区的名称
  const provinceName = areaColumns.value.province_list[data.selectedValues[0]]
  const cityName = areaColumns.value.city_list[data.selectedValues[1]]
  const countyName = areaColumns.value.county_list[data.selectedValues[2]]
  profile.value.fullLocation = `${provinceName} ${cityName} ${countyName}`

  //3.3记录省市区的编码
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
}

// 4. 选择职业
const professionList = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  // console.log(data.selectedValues)
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues[0]
}
const profession = ref<string[]>([])

// 5. 获取个人资料
const profile = ref<ProfileInfo>({} as ProfileInfo)
const getProfile = async () => {
  try {
    //5.1 开启提示
    showLoadingToast({ message: '正在加载中...', duration: 0, forbidClick: true })
    //5.2 发请求拿数据
    const res = await http.get<MkResponse<ProfileInfo>>('/member/profile')
    profile.value = res.data.result
    // console.log(profile.value)
    //5.4 取出生日给到页面
    birthday.value = res.data.result.birthday.split('-')
    //5.5 取出职业给到页面
    profession.value.push(res.data.result.profession)
  } finally {
    //5.3 关闭提示
    closeToast()
  }
}
getProfile()

//6.保存资料
const isLoading = ref(false)
const onSave = async () => {
  //6.1 非空处理
  if (!profile.value.nickname) {
    return showToast('昵称不能为空')
  }

  //6.2 调用接口
  try {
    isLoading.value = true
    mk.vibrator() //传感器
    await http.put('/member/profile', profile.value)

    //修改原生侧数据
    const user = mk.queryUser()
    user.nickname = profile.value.nickname
    mk.updateUser(user)
    showToast('保存资料成功')
  } catch (error) {
    showToast('保存资料失败')
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar">
      </van-image>
      <div class="avatar-btn" @click="showAvatarSheet = true">
        <span>修改头像</span>
      </div>

      <!-- 选择头像动作弹层 -->
      <van-action-sheet
        v-model:show="showAvatarSheet"
        :actions="[{ name: '相册' }, { name: '拍照' }]"
        cancel-text="取消"
        close-on-click-action
        @select="selectAvatarSheet"
      />
    </div>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly />
      <van-field label="昵称" v-model="profile.nickname" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>

      <van-field
        v-model="profile.birthday"
        label="生日"
        placeholder="请选择日期"
        readonly
        @click="showBirthdayPopup = true"
      />
      <!-- 选择生日弹层 -->
      <van-popup v-model:show="showBirthdayPopup" round position="bottom">
        <van-date-picker
          v-model="birthday"
          title="选择日期"
          @cancel="showBirthdayPopup = false"
          @confirm="onChangeBirthday"
          :min-date="new Date('1980-01-01')"
          :max-date="new Date()"
        />
      </van-popup>

      <van-field
        v-model="profile.fullLocation"
        label="所在地"
        placeholder="请选择所在地"
        readonly
        @click="showLocationPopup = true"
      />
      <!-- 选择所在地弹层 -->
      <van-popup v-model:show="showLocationPopup" round position="bottom">
        <van-area
          title="选择所在地"
          :area-list="areaColumns"
          @cancel="showLocationPopup = false"
          @confirm="onSelectedLocation"
        />
      </van-popup>

      <van-field
        v-model="profile.profession"
        label="职业"
        placeholder="请选择职业"
        readonly
        @click="showProfessionPopup = true"
      />
      <!-- 选择职业弹层 -->
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <van-picker
          title="选择职业"
          :columns="professionList"
          @confirm="onChangeProfession"
          @cancel="showProfessionPopup = false"
        />
      </van-popup>
    </van-cell-group>
    <div class="submit">
      <van-button
        :loading="isLoading"
        loading-text="正在提交..."
        round
        block
        type="primary"
        @click="onSave"
        >保存资料</van-button
      >
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

/* 
  默认情况下, 无法修改组件内容的样式
  如果要改, 请深度穿透
  ::v-deep()
*/
.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>